package Volume2.ch1;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

/**
 * 7:optional类型
 * @Auther jacob
 * @Date 2020/8/9 20:06
 */
public class OptionalTest {

    private static final String FIND_WORD = "b";

    public static void main(String[] args) throws IOException {
        Path path = Paths.get("src/Volume2/ch1/words.txt");
        String contents = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
        List<String> wordList = Arrays.asList(contents.split("\n"));

        Optional<String> optionalValue = wordList.stream().filter(s -> s.contains(FIND_WORD)).findFirst();
        System.out.println(optionalValue.orElse("No word") + " contains " + FIND_WORD);

        Optional<String> optionalString = Optional.empty();
        String result = optionalString.orElse("N/A");
        System.out.println("result: " + result);
        result = optionalString.orElseGet(() -> Locale.getDefault().getDisplayName());
        System.out.println("result: " + result);

//        try {
//            result = optionalString.orElseThrow(IllegalStateException::new);
//            System.out.println("result: " + result);
//
//        } catch (Throwable t){
//            t.printStackTrace();
//        }

        optionalValue = wordList.stream().filter(s -> s.contains(FIND_WORD)).findFirst();
        optionalValue.ifPresent(s -> System.out.println(s + " contains " + FIND_WORD));


        Set<String> results = new HashSet<>();
        optionalValue.ifPresent(results::add);
        results.forEach(System.out::println);

        Optional<Boolean> added = optionalValue.map(results::add);
        System.out.println(added);

        System.out.println(inverse(4.0).flatMap(OptionalTest::squareRoot));
        System.out.println(inverse(-1.0).flatMap(OptionalTest::squareRoot));
        System.out.println(inverse(0.0).flatMap(OptionalTest::squareRoot));



    }

    public static Optional<Double> inverse(Double x){
        return x == 0 ? Optional.empty() : Optional.of(1/x);
    }

    public static Optional<Double> squareRoot(Double x){
        return  x < 0 ? Optional.empty() : Optional.of(Math.sqrt(x));
    }

}
